package com.write.program.socket.util;

import com.write.program.socket.ServerSocketService;
import com.write.program.socket.message.LoginMessage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hzniufanglong
 * Date: 2019-11-21
 * Time: 12:57
 */
public class ServerLoginUtil {

    //解析credentials文件得到的所有账号信息
    private static HashMap<String, UserInfo> userInfoMap = new HashMap<>();

    /**
     * 所有账号与密码解析
     *
     * @param blockDurationSecond
     */
    public static void init(int blockDurationSecond) {
        String path = ServerLoginUtil.class.getResource("/credentials.txt").getPath();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(URLDecoder.decode(path)))));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                UserInfo userInfo = new UserInfo();
                userInfo.userName = line.split(" ")[0];
                userInfo.password = line.split(" ")[1];
                userInfoMap.put(userInfo.userName, userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 进行登陆和记录
     *
     * @param loginInfo
     * @return
     */
    public static boolean checkAndLogin(ServerSocketService.LoginInfo loginInfo) {
        UserInfo userInfo = userInfoMap.get(loginInfo.userName);
        return userInfo != null && loginInfo.password.equals(userInfo.password);
    }

    /**
     * 是否存在
     * @param username
     * @return
     */
    public static boolean contains(String username) {
        return userInfoMap.containsKey(username);
    }

    private static class UserInfo {
        private String userName;
        private String password;
    }
}
